package edu.rit.drh4818.raytracing.shaders;

import java.awt.Color;

import edu.rit.drh4818.raytracing.light.ColorMixer;
import edu.rit.drh4818.raytracing.util.Intersection;
import edu.rit.drh4818.raytracing.util.Ray;
import edu.rit.drh4818.raytracing.util.Scene;
import edu.rit.drh4818.raytracing.util.SuperSampling;

/**
 * @author Darren Headrick
 *
 */
public class Illuminate implements Shader
{
	private Shader local;
	
	public Illuminate( Shader local )
	{
		this.local = local;
	}
	
	public Color getColor(Intersection in, int depth) 
	{
		if( in == Intersection.NONE ) return Scene.instance.background;
		Color local = this.local.getColor( in, depth );

		if( depth+1 >= Scene.instance.MAX_DEPTH ) return local; 
		boolean totalInternal = false;
		
		if( in.obj.prop.kt > 0 )
		{
			Ray ray = in.ray.getTransmittedRay(in, in.obj.prop.n, 1F);
			if( ray != null ) 
			{
				Intersection next = ray.findNearestIntersection();
				local = ColorMixer.add( local, 
						ColorMixer.multiply( 
								next.getColor(depth + 1), 
								in.obj.prop.kt ) );
			}
			else  
			{
				totalInternal = true;
			}
		}
		
		if( in.obj.prop.kr > 0 || totalInternal )
		{
			Ray source = new Ray( in.getX(), in.getY(), in.getZ(),
					-in.ray.xd, -in.ray.yd, -in.ray.zd );
					
			Ray reflected = source.getReflectedRay( in );
			if( reflected != null )
			{
				Color tmp;
				if( Scene.instance.SUPERSAMPLING_MIRROR )
				{
					tmp = SuperSampling.getColor( reflected, 50, 1, depth + 1 );
				}
				else
				{
					tmp = reflected.findNearestIntersection().getColor( depth + 1 );
				}
				float factor = in.obj.prop.kr;
				if( totalInternal ) factor += in.obj.prop.kt;
				local = ColorMixer.add( ColorMixer.multiply( tmp, factor ), local );
			}
		}

		return local;
	}

}
